class CourseSectionPanel {
    constructor(app) {
        this.app = app;
    }

    initCourseManagement() {
        // 等待DOM更新完成后再绑定事件
        setTimeout(() => {
            const coursePanel = document.getElementById('course-panel');
            if (coursePanel) {
                // 添加课程按钮功能
                const addCourseBtn = coursePanel.querySelector('#add-course-btn');
                if (addCourseBtn) {
                    // 先移除可能存在的旧事件监听器，避免重复绑定
                    addCourseBtn.removeEventListener('click', this.addCourseClickListener);
                    // 保存监听器引用以便后续移除
                    this.addCourseClickListener = () => this.showAddCourseModal();
                    addCourseBtn.addEventListener('click', this.addCourseClickListener);
                }

                // 搜索功能
                const searchInput = coursePanel.querySelector('.search-input');
                if (searchInput) {
                    searchInput.addEventListener('input', (e) => this.handleCourseSearch(e));
                }
            }
        }, 0);
    }

    async loadCoursesForStage(stageId) {
        try {
            const response = await this.app.authenticatedFetch(`/api/web/course/getAllCourse?csid=${stageId}`);
            const result = await response.json();
            
            if (result.code === 200) {
                const courses = result.data || [];
                const tbody = document.querySelector('#courses-table-body');
                tbody.innerHTML = '';

                // 加载行模板
                const rowTemplateResponse = await fetch('/templates/course-row.html');
                const rowTemplateText = await rowTemplateResponse.text();
                const parser = new DOMParser();
                const doc = parser.parseFromString(rowTemplateText, 'text/html');
                const rowElement = doc.querySelector('tbody tr');

                courses.forEach(course => {
                    const row = rowElement.cloneNode(true);
                    const defaultAvatarUrl = Utils.buildFullUrl('/images/default-avatar.png');
                    
                    // 使用ID直接获取并填充数据
                    const courseIdElement = row.querySelector('#course-id');
                    if (courseIdElement) {
                        courseIdElement.textContent = course.id;
                    }
                    
                    const courseStageTitleElement = row.querySelector('#course-stage-title');
                    if (courseStageTitleElement) {
                        courseStageTitleElement.textContent = this.app.currentStage ? this.app.currentStage.title : '未知阶段';
                    }
                    
                    const courseTitleElement = row.querySelector('#course-title');
                    if (courseTitleElement) {
                        courseTitleElement.textContent = course.title;
                    }
                    
                    // 处理封面图片
                    const courseCoverElement = row.querySelector('#course-cover');
                    if (courseCoverElement && course.cover) {
                        const img = document.createElement('img');
                        img.src = course.cover;
                        img.alt = '封面';
                        img.style.cssText = 'max-width: 100px; max-height: 60px;';
                        img.setAttribute('data-default', defaultAvatarUrl);
                        img.addEventListener('error', function() {
                            this.src = this.getAttribute('data-default');
                        });
                        courseCoverElement.appendChild(img);
                    }
                    
                    const courseSynopsisElement = row.querySelector('#course-synopsis');
                    if (courseSynopsisElement) {
                        courseSynopsisElement.textContent = course.synopsis || '';
                    }
                    
                    const courseCreateDateElement = row.querySelector('#course-create-date');
                    if (courseCreateDateElement) {
                        courseCreateDateElement.textContent = Utils.formatDate(course.create_date) || '';
                    }
                    
                    const courseUpdateDateElement = row.querySelector('#course-update-date');
                    if (courseUpdateDateElement) {
                        courseUpdateDateElement.textContent = Utils.formatDate(course.updata_date) || '';
                    }
                    
                    // 设置按钮属性
                    const viewBtn = row.querySelector('#course-view-btn');
                    if (viewBtn) {
                        viewBtn.setAttribute('data-id', course.id);
                        viewBtn.setAttribute('data-title', course.title);
                    }
                    
                    const editBtn = row.querySelector('#course-edit-btn');
                    if (editBtn) {
                        editBtn.setAttribute('data-id', course.id);
                        editBtn.setAttribute('data-csid', course.csid);
                        editBtn.setAttribute('data-title', course.title);
                        editBtn.setAttribute('data-synopsis', course.synopsis || '');
                        editBtn.setAttribute('data-cover', course.cover || '');
                    }
                    
                    const deleteBtn = row.querySelector('#course-delete-btn');
                    if (deleteBtn) {
                        deleteBtn.setAttribute('data-id', course.id);
                    }
                    
                    tbody.appendChild(row);

                    // 绑定查看内容按钮事件
                    if (viewBtn) {
                        viewBtn.addEventListener('click', (e) => {
                            const courseId = e.target.getAttribute('data-id');
                            const courseTitle = e.target.getAttribute('data-title');
                            this.app.courseContentPanel.selectCourseContentSubPanel(courseId, courseTitle);
                        });
                    }

                    // 绑定删除按钮事件
                    if (deleteBtn) {
                        deleteBtn.addEventListener('click', (e) => {
                            const courseId = parseInt(e.target.getAttribute('data-id'));
                            const courseTitle = e.target.closest('tr').querySelector('#course-title').textContent;
                            Utils.confirmAndDelete(courseTitle, () => this.deleteCourse(courseId, courseTitle));
                        });
                    }
                });

                // 绑定所有编辑按钮事件
                tbody.querySelectorAll('#course-edit-btn').forEach(button => {
                    button.addEventListener('click', (e) => {
                        const courseData = {
                            id: parseInt(e.target.getAttribute('data-id')),
                            csid: parseInt(e.target.getAttribute('data-csid')),
                            title: e.target.getAttribute('data-title'),
                            synopsis: e.target.getAttribute('data-synopsis'),
                            cover: e.target.getAttribute('data-cover')
                        };
                        this.showEditCourseModal(courseData);
                    });
                });

                // 重新绑定搜索功能
                const searchInput = document.querySelector('#course-panel .search-input');
                if (searchInput) {
                    searchInput.addEventListener('input', (e) => this.handleCourseSearch(e));
                }

                // 如果没有课程，显示提示信息
                if (courses.length === 0) {
                    const row = document.createElement('tr');
                    row.innerHTML = `<td colspan="8" style="text-align: center;">该阶段下暂无课程节选</td>`;
                    tbody.appendChild(row);
                }
            } else {
                console.error('获取课程节选失败:', result.msg);
                Utils.showError(document.querySelector('#courses-table-body'), '获取课程节选失败');
            }
        } catch (error) {
            console.error('加载课程节选数据失败:', error);
            Utils.showError(document.querySelector('#courses-table-body'), '加载课程节选数据失败');
        }
    }

    async showAddCourseModal() {
        // 检查是否已选择阶段
        if (!this.app.currentStage) {
            alert('请先选择一个课程阶段');
            return;
        }

        try {
            // 加载模态框模板
            const response = await fetch('/templates/course-modal.html');
            const template = await response.text();
            
            // 创建添加课程模态框，自动使用当前选中的阶段
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.id = 'add-course-modal';
            modal.innerHTML = template;
            
            // 设置标题
            const titleElement = modal.querySelector('h3');
            if (titleElement) {
                titleElement.textContent = '添加课程节选';
            }
            
            // 设置按钮文本
            const submitButton = modal.querySelector('.modal-footer .btn.primary');
            if (submitButton) {
                submitButton.textContent = '添加';
            }
            
            // 填充阶段信息
            const stageTitleInput = modal.querySelector('#course-stage-title');
            const csidInput = modal.querySelector('#course-csid');
            
            if (stageTitleInput) {
                stageTitleInput.value = this.app.currentStage.title;
            }
            if (csidInput) {
                csidInput.value = this.app.currentStage.id;
            }

            document.body.appendChild(modal);

            // 绑定事件
            const closeBtn = modal.querySelector('.close');
            const cancelBtn = modal.querySelector('#cancel-course');
            const form = modal.querySelector('#course-form');
            const coverInput = modal.querySelector('#course-cover');

            const closeModal = () => {
                if (modal && modal.parentNode) {
                    modal.remove();
                }
            };

            if (closeBtn) {
                closeBtn.addEventListener('click', closeModal);
            }

            if (cancelBtn) {
                cancelBtn.addEventListener('click', closeModal);
            }

            // 图片预览功能
            if (coverInput) {
                coverInput.addEventListener('change', (e) => Utils.handleImagePreview(e, 'course-cover-preview'));
            }

            // 表单提交事件
            form.addEventListener('submit', (e) => this.handleAddCourseSubmit(e, form));

            // 显示模态框
            modal.style.display = 'block';
        } catch (error) {
            console.error('加载模态框模板失败:', error);
            alert('加载模态框失败，请查看控制台了解详情');
        }
    }

    async handleAddCourseSubmit(e) {
        e.preventDefault();
        
        const csid = document.getElementById('course-csid').value;
        const title = document.getElementById('course-title').value;
        const synopsis = document.getElementById('course-synopsis').value;
        const coverFile = document.getElementById('course-cover').files[0];

        // 验证必填字段
        if (!title.trim()) {
            alert('请输入课程名称');
            return;
        }

        if (!csid) {
            alert('请选择课程阶段');
            return;
        }

        // 创建FormData对象
        const formData = new FormData();
        formData.append('csid', csid);
        formData.append('title', title.trim());
        formData.append('synopsis', synopsis.trim());
        
        if (coverFile) {
            formData.append('cover', coverFile);
            // 设置封面裁剪尺寸
            formData.append('coverWidth', 372);
            formData.append('coverHeight', 266);
        }

        try {
            const response = await this.app.authenticatedFetch('/api/web/course/addCourse', {
                method: 'POST',
                body: formData
            });

            const resultText = await response.text();
            
            let result;
            try {
                result = JSON.parse(resultText);
            } catch (parseError) {
                console.error('解析响应失败:', resultText);
                throw new Error('服务器响应格式错误');
            }
            
            if (result.code === 200) {
                alert('课程节选添加成功');
                // 关闭模态框
                const modal = document.getElementById('add-course-modal');
                if (modal) {
                    modal.remove();
                }
                // 重新加载课程节选列表
                this.loadCoursesForStage(csid);
            } else {
                alert('添加失败: ' + (result.msg || '未知错误'));
            }
        } catch (error) {
            console.error('添加课程节选失败:', error);
            alert('添加课程节选失败: ' + error.message);
        }
    }

    /**
     * 获取所有课程阶段
     * @returns {Promise<Array>} 课程阶段列表
     */
    async getAllStages() {
        try {
            const response = await this.app.authenticatedFetch('/api/web/course/getAllStage');
            const result = await response.json();
            if (result.code === 200) {
                return result.data || [];
            } else {
                console.error('获取课程阶段失败:', result.msg);
                return [];
            }
        } catch (error) {
            console.error('获取课程阶段数据失败:', error);
            return [];
        }
    }

    async showEditCourseModal(courseData) {
        // 先获取所有阶段列表
        const stages = await this.getAllStages();
        
        try {
            // 加载模态框模板
            const response = await fetch('/templates/course-modal.html');
            const template = await response.text();
            
            // 创建编辑模态框
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.id = 'edit-course-modal';
            modal.innerHTML = template;
            
            // 设置标题
            const titleElement = modal.querySelector('h3');
            if (titleElement) {
                titleElement.textContent = '编辑课程节选';
            }
            
            // 设置按钮文本
            const submitButton = modal.querySelector('.modal-footer .btn.primary');
            if (submitButton) {
                submitButton.textContent = '更新';
            }
            
            // 填充表单数据
            const idInput = modal.querySelector('#course-id');
            const titleInput = modal.querySelector('#course-title');
            const synopsisInput = modal.querySelector('#course-synopsis');
            const coverPreview = modal.querySelector('#course-cover-preview');
            
            if (idInput) idInput.value = courseData.id;
            if (titleInput) titleInput.value = courseData.title;
            if (synopsisInput) synopsisInput.value = courseData.synopsis || '';
            
            // 显示当前封面图片
            if (courseData.cover && coverPreview) {
                const defaultAvatarUrl = Utils.buildFullUrl('/images/default-avatar.png');
                coverPreview.innerHTML = `
                    <img src="${courseData.cover}" style="max-width: 200px; max-height: 200px; margin-top: 10px;" alt="当前封面" data-default="${defaultAvatarUrl}">
                `;
                
                // 为图片绑定错误处理事件
                const previewImg = coverPreview.querySelector('img');
                if (previewImg) {
                    previewImg.addEventListener('error', function() {
                        this.src = this.getAttribute('data-default');
                    });
                }
            }
            
            // 填充阶段信息
            const stageTitleInput = modal.querySelector('#course-stage-title');
            const csidInput = modal.querySelector('#course-csid');
            
            if (stageTitleInput) {
                // 查找当前阶段的标题
                const currentStage = stages.find(stage => stage.id === courseData.csid);
                stageTitleInput.value = currentStage ? currentStage.title : '未知阶段';
            }
            if (csidInput) {
                csidInput.value = courseData.csid;
            }

            document.body.appendChild(modal);

            // 绑定事件
            const closeBtn = modal.querySelector('.close');
            const cancelBtn = modal.querySelector('#cancel-course');
            const form = modal.querySelector('#course-form');
            const coverInput = modal.querySelector('#course-cover');

            const closeModal = () => {
                if (modal && modal.parentNode) {
                    modal.remove();
                }
            };

            if (closeBtn) {
                closeBtn.addEventListener('click', closeModal);
            }

            if (cancelBtn) {
                cancelBtn.addEventListener('click', closeModal);
            }

            // 图片预览功能
            if (coverInput) {
                coverInput.addEventListener('change', (e) => Utils.handleImagePreview(e, 'course-cover-preview'));
            }

            // 表单提交事件
            form.addEventListener('submit', (e) => this.handleEditCourseSubmit(e, form));

            // 显示模态框
            modal.style.display = 'block';
        } catch (error) {
            console.error('加载模态框模板失败:', error);
            alert('加载模态框失败，请查看控制台了解详情');
        }
    }

    async handleEditCourseSubmit(e, form) {
        e.preventDefault();
        
        // 直接从表单获取元素，而不是通过全局查找
        const idElement = form.querySelector('#course-id');
        const csidElement = form.querySelector('#course-csid');
        const titleElement = form.querySelector('#course-title');
        const synopsisElement = form.querySelector('#course-synopsis');
        const coverInput = form.querySelector('#course-cover');
        
        if (!idElement || !csidElement || !titleElement || !synopsisElement) {
            alert('表单元素缺失，请重新打开编辑课程窗口');
            return;
        }
        
        const id = idElement.value;
        const csid = csidElement.value;
        const title = titleElement.value;
        const synopsis = synopsisElement.value || '';
        const coverFile = coverInput && coverInput.files && coverInput.files.length > 0 ? coverInput.files[0] : null;

        // 验证必填字段
        if (!title.trim()) {
            alert('请输入课程名称');
            return;
        }

        if (!csid) {
            alert('请选择课程阶段');
            return;
        }

        // 创建FormData对象
        const formData = new FormData();
        formData.append('id', id);
        formData.append('csid', csid);
        formData.append('title', title.trim());
        formData.append('synopsis', synopsis.trim());
        
        if (coverFile) {
            formData.append('cover', coverFile);
            // 设置封面裁剪尺寸
            formData.append('coverWidth', 800);
            formData.append('coverHeight', 600);
        }

        try {
            const response = await this.app.authenticatedFetch('/api/web/course/updateCourse', {
                method: 'POST',
                body: formData
            });

            const resultText = await response.text();
            
            let result;
            try {
                result = JSON.parse(resultText);
            } catch (parseError) {
                console.error('解析响应失败:', resultText);
                throw new Error('服务器响应格式错误');
            }
            
            if (result.code === 200) {
                alert('课程节选更新成功');
                // 关闭模态框
                const modal = document.getElementById('edit-course-modal');
                if (modal) {
                    modal.remove();
                }
                // 重新加载课程节选列表
                this.loadCoursesForStage(csid);
            } else {
                alert('更新失败: ' + (result.msg || '未知错误'));
            }
        } catch (error) {
            console.error('更新课程节选失败:', error);
            alert('更新课程节选失败: ' + error.message);
        }
    }

    async deleteCourse(courseId, courseTitle) {
        try {
            const response = await this.app.authenticatedFetch(`/api/web/course/deleteCourse/${courseId}`, {
                method: 'DELETE'
            });

            const resultText = await response.text();
            
            let result;
            try {
                result = JSON.parse(resultText);
            } catch (parseError) {
                console.error('解析响应失败:', resultText);
                throw new Error('服务器响应格式错误');
            }
            
            if (result.code === 200) {
                alert(`课程节选"${courseTitle}"删除成功`);
                // 重新加载课程节选列表
                if (this.app.currentStage) {
                    this.loadCoursesForStage(this.app.currentStage.id);
                }
            } else {
                alert('删除失败: ' + (result.msg || '未知错误'));
            }
        } catch (error) {
            console.error('删除课程节选失败:', error);
            alert('删除课程节选失败: ' + error.message);
        }
    }

    handleCourseSearch(e) {
        const searchTerm = e.target.value.toLowerCase();
        const courseRows = document.querySelectorAll('#courses-table-body tr');

        courseRows.forEach(row => {
            const title = row.querySelector('#course-title').textContent.toLowerCase();
            const synopsis = row.querySelector('#course-synopsis').textContent.toLowerCase();

            if (title.includes(searchTerm) || synopsis.includes(searchTerm)) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    }
}